import backtrader as bt

# 双移动平均线策略
class DoubleMovingAverageStrategy(bt.Strategy):
    params = (
        ("fast_period", 10),
        ("slow_period", 30),
    )

    def __init__(self):
        self.fast_ma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.fast_period
        )
        self.slow_ma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.slow_period
        )

    def next(self):
        if self.fast_ma[0] > self.slow_ma[0] and self.position.size < 0:
            self.close()
            self.buy()
        elif self.fast_ma[0] < self.slow_ma[0] and self.position.size > 0:
            self.close()
            self.sell()


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(DoubleMovingAverageStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
